<template>
  <div class="relative leading-[0px]">
    <!--    单行-->
    <input v-if="type === TYPE_TEXT"
           class="border-gray-200 dark:border-zinc-600 dark:bg-zinc-800 duration-100 dark:text-zinc-400 border outline-0
                  py-0.5 px-1 text-sm rounded-sm focus:border-blue-400 w-full"
           type="text" v-model="text" :maxlength="max"/>
    <!--    多行-->
    <textarea v-if="type === TYPE_AREA" v-model="text"
              class="border-gray-200 dark:border-zinc-600 dark:bg-zinc-800 duration-100 dark:text-zinc-400 border outline-0
                     py-0.5 px-1 text-sm rounded-sm focus:border-blue-400 w-full" rows="5" :maxlength="max"></textarea>
    <!--   错误提示-->
    <span v-if="max" class="absolute right-1 bottom-0.5 text-zinc-400 text-xs"
          :class="{'text-red-700' :currentNumber === parseInt(max)}">{{ currentNumber }} / {{ max }}</span>
  </div>
</template>

<script>
//单行
const TYPE_TEXT = 'text'
//多行
const TYPE_AREA = 'textarea'
</script>
<script setup>
import {useVModel} from "@vueuse/core";
import {computed} from "vue";

const props = defineProps({
  //1.双向绑定 v-model
  modelValue: {
    type: String,
    required: true
  },
  type: {
    type: String,
    default: TYPE_TEXT,
    validator(value) {
      //1.获取所有的可选项
      const arr = [TYPE_TEXT, TYPE_AREA]
      //2.开发者指定的风格在可选项中
      const result = arr.includes(value)
      if (!result) {
        throw new Error(`您的type必须是${arr.join('、')}中的一个`)
      }
      return result
    }
  },
  //3.max,
  max: {
    type: [String, Number]
  }
})
const emits = defineEmits(['update:modelValue'])
//输入的字符
const text = useVModel(props)
//输入的字符数
const currentNumber = computed(() => {
  return text.value?.length
})
</script>
